<?php

require_once 'etc/config.php';
class Stock {
  private $mysqli;

  public function __construct()
  {
    $mysqli = new mysqli(HOST, USER, PASS, DB);
    $mysqli->set_charset("utf8");
    $this->mysqli = $mysqli;
  }

  public function getCurrent($code)
  {
    $url  = 'http://hq.sinajs.cn/list='.$code;
    $content = file_get_contents($url);
    $content = substr($content, strpos($content, '"')+1, -3);
    $array   = explode(',', $content);
    $array[0]= iconv('GB2312', 'UTF-8', $array[0]);
    $array[] = $array[3] - $array[2];
    $array[] = round($array[32]*100/$array[2], 2);
    $keys    = array('name','kaipan','shoupan', 'current', 'highest', 'lowest', 'buy_price', 'sell_price', 'turnover_count', 'turnover_value', 'buy1_count', 'buy1_price','buy2_count', 'buy2_price','buy3_count', 'buy3_price','buy4_count', 'buy4_price','buy5_count', 'buy5_price','sell1_count', 'sell1_price','sell2_count', 'sell2_price','sell3_count', 'sell3_price','sell4_count', 'sell4_price','sell5_count', 'sell5_price','date', 'time', 'increase', 'increase_percent');
    return array_combine($keys, $array);
  }

  public function update($code, $data=null)
  {
    if (!$data) {
      $data = $this->getCurrent($code);
    }

    foreach ($data as $key=>$value) {
      $keyValue[] = "$key = '$value'";
    }
    $updateSql = implode(',', $keyValue);

    if ($row = $this->fetch($code)) {
      $sql = "UPDATE my_stock SET $updateSql WHERE id = " . $row['id'];
    } else {
      $sql = "INSERT INTO my_stock SET code = '$code', $updateSql";
    }

    $this->mysqli->query($sql);
    $now = date('Y-m-d H:i:s');
    $sql = "INSERT INTO price_history SET code = '$code', runtime = '$now', $updateSql";
    $this->mysqli->query($sql);
  }

  public function fetch($code)
  {
    $sql = "SELECT * FROM my_stock WHERE code = '$code'";
    $result = $this->mysqli->query($sql);
    $row    = $result->fetch_array();
    return $row;
  }

  public function getMonitors()
  {
    $monitors = array();

    $sql = "SELECT * FROM monitor";
    $result = $this->mysqli->query($sql);
    while ($row = $result->fetch_array()) {
      $monitors[] = $row;
    }

    return $monitors;
  }

  public function sendNotice($content)
  {
    require_once 'lib/XMPPHP/XMPP.php';
    $conn = new XMPPHP_XMPP('talk.google.com', 5222, GTALK_USERNAME, GTALK_PASSWORD, 'xmpphp', 'gmail.com', $printlog=False);
    $conn->connect();
    $conn->processUntil('session_start');
    $userEmail= 'seven_yang@cn.bposolutions.com';
    $conn->message($userEmail, $content);
    $conn->disconnect();
    $this->setNoticeLog($content);
  }

  public function setNoticeLog($content)
  {
    $now = date('Y-m-d H:i:s');
    $sql = "INSERT INTO notice SET content = '$content', datetime = '$now'";
    $this->mysqli->query($sql);
  }

  public function newMonitor($code, $profitLimit, $lowerLimit)
  {
    $sql = "SELECT id FROM monitor WHERE code = '$code'";
    $result = $this->mysqli->query($sql);
    $row = $result->fetch_array();
    if ($row) {
      return false;
    }
    $sql = "SELECT id FROM my_stock WHERE code = '$code'";
    $result = $this->mysqli->query($sql);
    $row = $result->fetch_array();
    $stockId = $row['id'];
    $status = !$profitLimit && !$lowerLimit ? '0' : '1';
    $sql = "INSERT INTO monitor VALUES (NULL,$stockId, '$code', '$profitLimit', '$lowerLimit', '$status')";
    return $this->mysqli->query($sql);
  }

  public function updateMonitor($id, $profitLimit, $lowerLimit, $status)
  {
    $sql = "UPDATE monitor SET profit_price = '$profitLimit', loss_price = '$lowerLimit', status = '$status' WHERE id = $id";
    return $this->mysqli->query($sql);
  }

  public function deleteMonitor($id)
  {
    $sql = "DELETE FROM monitor WHERE id = $id";
    return $this->mysqli->query($sql);
  }

  public function disableAlarm($id)
  {
    $sql = "UPDATE monitor SET status = 0 WHERE id = $id";
    return $this->mysqli->query($sql);
  }

  public function updateAlarm($id, $rise)
  {
    $sql = "SELECT * FROM monitor WHERE id = $id";
    $result = $this->mysqli->query($sql);
    $row = $result->fetch_array();
    $profitLimit = $row['profit_price'];
    $lossLimit   = $row['loss_price'];

    $percent = 'up' == $rise ? 1.01 : 0.99;
    $newProfitLimit = round($profitLimit * $percent, 2);
    $newLossLimit   = round($lossLimit * $percent, 2);
  
    $sql = "UPDATE monitor SET profit_price = $newProfitLimit, loss_price = $newLossLimit WHERE id = $id";
    $this->mysqli->query($sql);
  }
}
